/*
* 岗位管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../config/utils");
// 引入日志
const log = require("../log");

// 获取所有岗位列表
router.get("/list", async (req, res) => {
    console.log("===========获取岗位列表接口============");
    // 获取参数
    let { pageNum, pageSize, postCode, postName, status } = req.query;
    // 拼接sql语句
    let sql = "select * from sys_post";
    let sql_where = ` where 1=1`;
    if(postCode){
        sql_where += ` and post_code like '%${postCode}%'`;
    }
    if(postName){
        sql_where += ` and post_name like '%${postName}%'`;
    }
    if(status){
        sql_where += ` and status = '${status}'`;
    }
    if(postCode || postName || status ){
        sql += sql_where;
    }
    
    // 分页
    sql += ` limit ${(pageNum-1)*pageSize}, ${pageSize}`;
    // 查询数据库
    db.query("查询岗位列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询岗位列表失败", data: err});
            return;
        }
        // 查询总数
        db.query("查询岗位总数", `select count(*) as count from sys_post ${sql_where}`, (err, count)=>{
            if(err){
                res.send({code: 500, msg: "查询岗位总数失败", data: err});
                return;
            }
            if(result.length > 0){
                 // 变量Json数组key转成下划线第一个大写
                 result = result.map(item => {
                    return toCamelCase(item)
                })
                res.send({code: 200, msg: "查询岗位列表成功", rows: result, total: count[0].count});
            }else{
                res.send({code: 200, msg: "查询岗位列表成功", rows: [], total: 0});
            }
        })
    })
})

// 新增岗位
router.post("/", (req, res)=>{
    console.log("===========新增岗位接口============");
    // 获取参数
    let { postCode, postName, postSort, status, remark } = req.body;
    // 获取创建人
    let {username} = verifyToken(req.headers.authorization);
    // 获取创建时间
    let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 判断岗位名称和岗位编码是否重复
    db.query("查询岗位名称和岗位编码是否重复", `select * from sys_post where post_code = '${postCode}' or post_name = '${postName}'`, (err, sql_check_result)=>{
        if(err){
            res.send({code: 500, msg: "查询岗位名称和岗位编码是否重复失败", data: err});
            return;
        }
        if(sql_check_result.length > 0){
            res.send({code: 500, msg: "岗位名称或岗位编码已存在"});
            return;
        }
        // 插入数据库
        let sql = `insert into sys_post (post_code, post_name, post_sort, status, remark, create_by, create_time)
        values 
        ('${postCode}', '${postName}', '${postSort}', '${status}',
        ${remark ? "'"+remark+"'" : null}, '${username}', '${createTime}')`;
        db.query("新增岗位", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "新增岗位失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "新增岗位成功"});
            }else{
                res.send({code: 500, msg: "新增岗位失败"});
            }
        })
    })
})

// 查询单个岗位
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个岗位接口，正则匹配============");
    // 获取参数
    let url_arr = req.url.split("/");
    const id = url_arr[url_arr.length - 1];
   
    db.query("查询单个岗位", `select * from sys_post where post_id = ${id}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询单个岗位失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询单个岗位成功", data: result[0]});
        }else{
            res.send({code: 500, msg: "查询单个岗位失败"});
        }
    })
})

// 修改岗位
router.put("/", (req, res)=>{
    console.log("===========修改岗位接口============");
    // 获取参数
    let { postCode, postName, postSort, status, remark, postId } = req.body;
    // 获取修改人
    let {username} = verifyToken(req.headers.authorization);
    // 获取修改时间
    let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 判断岗位名称和岗位编码是否重复
    db.query("查询岗位名称和岗位编码是否重复", `select * from sys_post where (post_code = '${postCode}' or post_name = '${postName}') and post_id != ${postId}`, (err, sql_check_result)=>{
        if(err){
            res.send({code: 500, msg: "查询岗位名称和岗位编码是否重复失败", data: err});
            return;
        }
        if(sql_check_result.length > 0){
            res.send({code: 500, msg: "岗位名称或岗位编码已存在"});
            return;
        }
        // 修改数据库
        let sql = `update sys_post set post_code = '${postCode}', post_name = '${postName}', post_sort = '${postSort}', status = '${status}',
        remark = ${remark ? "'"+remark+"'" : null}, update_by = '${username}', update_time = '${updateTime}'
        where post_id = ${postId}`;
        db.query("修改岗位", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "修改岗位失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "修改岗位成功"});
            }else{
                res.send({code: 500, msg: "修改岗位失败"});
            }
        })
    })
})

// 删除岗位
router.delete("/:id", (req, res) => {
    console.log("===========删除岗位接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from sys_post where post_id in(${id})`;
    // 查询数据库
    db.query("删除岗位", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除岗位失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除岗位成功"})
        }else{
            res.send({code: 500, msg: "删除岗位失败"})
        }
    })
})

// 查询所有有效岗位
router.get("/listAll", (req, res) => {
    console.log("===========查询所有有效岗位接口============");

    let sql = `select * from sys_post where status = '0'`;
    // 查询数据库
    db.query("查询所有有效岗位", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "查询所有有效岗位失败", data: err});
            return
        }
        if (result.length > 0) {
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
               return toCamelCase(item)
           })
       }
       res.send({code: 200, msg: "查询所有有效岗位成功", data: result})
    })
})

module.exports = router;
